'use client';

import type { TBody, TOauthClientApiReviewState } from '@/types';
import type {
  IDifference,
  IOauthClientApi,
  IUpdateOauthClientApiStatusBody,
} from '@/interfaces';
import {
  OAUTH_CLIENT_API_REVIEW_STATE_KEY,
  OAUTH_CLIENT_API_REVIEW_STATE_LIST,
} from '@/lib/constant';
import useToast from '@/hooks/useToast';
import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { updateOauthClientApiStatus } from '@/services/api';
import diff from 'microdiff';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';
import { OauthClientAdminContext } from '@/contexts/admin/oauth/client';

export default function UpdateOauthClientInterfaceState({
  details,
}: {
  details: IOauthClientApi;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    reviewState: TOauthClientApiReviewState;
    reviewReason?: string;
  }>({
    reviewState: 'PENDING',
    reviewReason: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();
  const context = useContext(OauthClientAdminContext);

  const updateOauthClientApiStatusMutation = useMutation(
    async (variables: TBody<IUpdateOauthClientApiStatusBody>) => {
      await updateOauthClientApiStatus(variables);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        reviewState: details.reviewState || 'PENDING',
        reviewReason: details.reviewReason || '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          reviewState: details.reviewState,
          reviewReason: details.reviewReason || '',
        },
        {
          reviewState: form.reviewState,
          reviewReason: form.reviewReason || '',
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(
    e: ChangeEvent<HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      if (!details.reviewState) {
        show({
          type: 'DANGER',
          message: '修改客户端接口失败，数据不存在',
        });
        return;
      }

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      const cid = context.detailItem!.clientId;
      await updateOauthClientApiStatusMutation.mutateAsync({
        id: cid,
        data: {
          ...body,
          apiId: details.id + '',
        },
      });

      await queryClient.refetchQueries(
        ['/oauth', '/clients', '/apis', { cid }],
        {},
        { throwOnError: true },
      );

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateOauthClientApiStatusMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  function checkForm() {
    const { reviewState } = form;

    if (!reviewState) {
      throw '请选择开放认证客户端接口审核状态';
    }
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">审核状态</label>
            <select
              name="reviewState"
              value={form.reviewState}
              onChange={onChangeForm}
              className="form-select"
              aria-label="reviewState"
              placeholder="请选择审核状态"
            >
              {OAUTH_CLIENT_API_REVIEW_STATE_LIST.map((key) => {
                return (
                  <option key={key} value={key}>
                    {OAUTH_CLIENT_API_REVIEW_STATE_KEY[key]}
                  </option>
                );
              })}
            </select>
          </div>

          <div>
            <label className="form-label">审核理由</label>
            <textarea
              rows={1}
              name="reviewReason"
              className="form-control"
              value={form.reviewReason}
              onChange={onChangeForm}
              aria-describedby="reviewReason"
              placeholder="请输入审核理由"
            />
          </div>

          <button
            type="submit"
            disabled={updateOauthClientApiStatusMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateOauthClientApiStatusMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
